import { getMainLifeCycle} from '../const/mainLifeCycle'
import { findAppByRoute } from '../utils'
import { loadHtml } from '../loader'

export const lifecycle = async() => {
    const prevApp = findAppByRoute(window.__ORIGIN_APP__)
    const nextApp = findAppByRoute(window.__CURRENT_SUB_APP__)
    console.log(prevApp, nextApp)

    if (!nextApp) {
        return
    }

    if (prevApp && prevApp.unmount) {
        if (prevApp.proxy) {
            prevApp.proxy.inactive()
        }
        await destoryed(prevApp)
    }

    const app = await beforeLoad(nextApp)
    await mounted(app)
}

export const beforeLoad = async(app) => {
    await runMainLifeCycle('beforeLoad')
    app && app.bootstrap && app.bootstrap()
    const subApp = await loadHtml(app) // 获取子应用内容
    subApp && subApp.bootstrap && subApp.bootstrap() // ?
    return subApp
}

export const mounted = async(app) => {
    app && app.mount && app.mount({
        appInfo: app.appInfo,
        entry: app.entry
    })
    await runMainLifeCycle('mounted')
}

export const destoryed = async(app) => {
    app && app.unmount && app.unmount()
    await runMainLifeCycle('destoryed')
}
export const runMainLifeCycle = async type => {
    const mainLifeCycle = getMainLifeCycle()
    await Promise.all(mainLifeCycle[type].map(async item => await item()))
}
